# coding=utf-8
import time
import os
from apscheduler.schedulers.blocking import BlockingScheduler

from selenium import webdriver
import json
import time
import requests
from urllib.parse import urlencode
file = 'cookies.json'
reply_msg=''
logfile = 'log.log'
# 打开网址
def open_url(url,driver):
    driver.get(url)
    driver.delete_all_cookies()
    driver.implicitly_wait(5)
    driver.maximize_window()


# 向浏览器添加保存的cookies
def add_cookies(driver):
    fp = open(file, 'r')
    cookies = json.load(fp)
    fp.close()
    for cookie in cookies:
        driver.add_cookie(cookie)

def save_cookies(driver):
    cookies = driver.get_cookies()
    fp = open(file, 'w')
    jsonCookies = json.dumps(cookies)
    # 登录完成后，将cookie保存到本地文件
    with open(file, 'w') as f:
        f.write(jsonCookies)
    fp.close()

    # 关闭浏览器
def run(driver):
    global f_list
    global reply_msg
    driver.get("https://mp.toutiao.com/profile_v3/weitoutiao")
    time.sleep(3)
    articUrl = driver.find_element_by_xpath("//a[@class='src-pages-content-components-post-item-item-body-index-content'][1]").get_attribute("href")
    if articUrl not in f_list:
        send_reply(driver,articUrl,reply_msg)
        add_log(articUrl)
        print("reply Ok")
    else:
        print("now not flush")
def send_reply(driver,articUrl,reply_msg):
    driver.get(articUrl)
    driver.find_element_by_xpath("//textarea").click()
    time.sleep(1)
    driver.find_element_by_xpath("//textarea").send_keys(reply_msg)
    time.sleep(1)
    driver.find_element_by_xpath("//div[@class='c-submit']").click()

# open()
def add_log(logUrl):
    global f_list
    if logUrl not in f_list:
        f_list.append(logUrl)
        with open(logfile,"a+",encoding='utf-8') as log:
            log.write(logUrl+'\n')


if __name__ == '__main__':
    f_list = []
    with open("msg.txt","r+",encoding='utf-8') as msg:
        reply_msg = msg.read()
    try:
        with open(logfile,"r+",encoding='utf-8') as log:
            texts = log.readlines()
            for t in texts:
                f_list.append(t[:-1])
    except:
        open(logfile, "w+", encoding='utf-8').close()


    #进入进程

    # '''
    driver = webdriver.Firefox()
    open_url("https://www.toutiao.com", driver)
    time.sleep(3)
    # 添加cookies后刷新界面，实现免密登录
    add_cookies(driver)
    driver.refresh()
    key = input("请输入")
    if key == 'start':
        print("start")
    # save_cookies(driver)

    run(driver)

    # '''

    scheduler = BlockingScheduler()
    scheduler.add_job(run,'interval',seconds=90,args=[driver])
    scheduler.start()
    driver.close()
